package frame.system.mapper;

import frame.system.qo.AuthQo;
import frame.system.to.Permission;
import org.apache.ibatis.annotations.*;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
import java.util.Set;

/**
 * 对应表：sys_permission 对于实体类：Permission
 * <br>
 * @author PeiWentao
 * @since 2020-05-27 20:04
 */
public interface PermissionMapper extends Mapper<Permission> {

	// 字段
    String FIELDS = "t.pid,t.lv,t.name,t.url,t.type,t.shiro,t.icon,t.sorting,t.description,t.valid,t.create_time,t.update_time,t.id";
    // 表名 as 别名
    String TABLE = "sys_permission t";
    // mapper包名
    String PACKAGE = "frame.system.mapper";

    @Results({
        @Result(column = "id", property = "id",id = true)
    })
    @Select({"<script>SELECT ", FIELDS," FROM ", TABLE,
            " WHERE t.valid=#{valid}",
            "<when test='name!=null' > AND name LIKE CONCAT('%',#{name},'%')</when>",
            "<when test='type!=null' > AND `type`=#{type}</when>",
            "<when test='pid!=null and pid gt 1' > AND FIND_IN_SET(t.id, PermissionChild(#{pid}))</when>",
            "ORDER BY pid,sorting",
            "</script>"})
	List<Permission> pageList(AuthQo qo);

    @Select("SELECT id,pid,name,sorting,icon from sys_permission WHERE `type` ='1' AND valid = 1 ORDER BY sorting ASC,id ASC")
    List<Permission> allDirList();

    @Select("SELECT id,pid,name,sorting,icon from sys_permission WHERE `type` in('1','2','3') AND valid = 1 ORDER BY sorting ASC,id ASC")
    List<Permission> allPermissionList();
    // 查询用户的所有权限
    @Select({"SELECT t.id,t.pid,t.`name`,t.url,t.icon,t.shiro,t.type,t.sorting FROM ",
            "sys_user_2_role ur JOIN sys_role_2_permission rp ON ur.rid=rp.rid ",
            "JOIN sys_permission t ON rp.pid=t.id ",
            "WHERE t.type in ('1','2') AND t.valid=1 AND ur.uid=#{0}"})
    List<Permission> allPermissionListByUserId(Integer uid);

    @Select({"SELECT DISTINCT p.shiro FROM ",
            "sys_user u JOIN sys_user_2_role ur ON ur.uid ",
            "JOIN sys_role_2_permission rp ON ur.rid=rp.rid ",
            "JOIN sys_permission p ON rp.pid=p.id ",
            "WHERE p.shiro!='' AND p.valid=1 AND u.username=#{0}"})
    Set<String> allShiroListByUsername(String username);

    // 逻辑删除 删除资源同时删除其子节点
    @Update("UPDATE sys_permission SET valid='0' WHERE FIND_IN_SET(id, PermissionChild(#{0})) AND valid=1")
    int remove(Integer id);
    // 删除该资源与角色的关联
    @Delete("DELETE sys_role_2_permission WHERE FIND_IN_SET(pid, PermissionChild(#{0}))")
    int delete2Role(Integer id);


    // 根据角色ID级联查询资源
    @Select("SELECT t.name,t.shiro,t.id FROM " + TABLE + " WHERE t.valid=1 AND t.id in(SELECT pid FROM sys_role_2_permission a WHERE a.rid=#{0})")
    List<Permission> allListByRoleId(Integer rid);
 }
